<template>
  <div class="charge-container">
    <h1>窗口收费</h1>
    
    <!-- 患者搜索区域 -->
    <div class="search-section">
      <h3>患者搜索</h3>
      <el-form :model="searchForm" label-width="80px" inline>
        <el-form-item label="病历号：">
          <el-input v-model="searchForm.caseNumber" placeholder="请输入" style="width: 180px;" />
        </el-form-item>
        <el-form-item label="姓名：">
          <el-input v-model="searchForm.realName" placeholder="请选择" style="width: 180px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 患者信息区域 - 始终显示但内容可能为空 -->
    <div class="patient-info-section" v-show="true">
      <h3>患者信息</h3>
      <div class="patient-info-content">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名：">
              <el-input :value="patientInfo?.realName || ''" disabled placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="身份证号：">
              <el-input :value="patientInfo?.cardNumber || ''" disabled placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="性别：">
              <el-input :value="patientInfo?.gender || ''" disabled placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="年龄：">
              <el-input :value="patientInfo?.age || ''" disabled placeholder="请输入" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>

    <!-- 收费项目列表 -->
    <div class="items-section" v-if="patientInfo">
      <div class="total-price-section">
        <div class="total-price">
          <i class="el-icon-info"></i>
          总价格：<span class="price-amount">{{ totalPrice }}元</span>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="chargeItems"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="itemName" label="项目名称" width="200" />
        <el-table-column prop="price" label="单价" width="120" />
        <el-table-column prop="quantity" label="数量" width="120" />
      </el-table>

      <!-- 结算按钮 -->
      <div class="settle-section">
        <el-button type="primary" @click="handleSettle" :disabled="totalPrice <= 0">收费结算</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import patientApi from '@/api/patient.js'
import chargeApi from '@/api/charge.js'
import prescriptionApi from '@/api/prescription.js'
import registerApi from '@/api/register.js'

// 搜索表单
const searchForm = reactive({
  caseNumber: '',
  realName: ''
})

// 患者信息
const patientInfo = ref(null)
// 收费项目列表
const chargeItems = ref([])
// 加载状态
const loading = ref(false)
// 选中的项目
const selectedItems = ref([])

// 计算总价格
const totalPrice = computed(() => {
  if (selectedItems.value.length > 0) {
    return selectedItems.value.reduce((sum, item) => sum + (item.price * item.quantity), 0)
  }
  return 0
})

// 搜索患者信息
const handleSearch = async () => {
  if (!searchForm.caseNumber && !searchForm.realName) {
    ElMessage.warning('请输入病历号或姓名')
    return
  }

  loading.value = true
  try {
    // 清空之前的患者信息和收费项目
    patientInfo.value = null
    chargeItems.value = []
    selectedItems.value = []

    // 发送两个并行请求：一个获取患者信息，一个获取收费项目
    const [patientResponse, chargeItemsResponse] = await Promise.all([
      // 获取患者信息
      registerApi.patientSearch({
        caseNumber: searchForm.caseNumber,
        realName: searchForm.realName
      }),
      // 获取收费项目
      patientApi.search(searchForm)
    ])

    // 处理患者信息响应
  // axios 封装返回 { success, message, data }
  if (patientResponse.success && patientResponse.data) {
      // 直接使用data对象
      patientInfo.value = {
        id: patientResponse.data.id,
        realName: patientResponse.data.realName,
        caseNumber: patientResponse.data.caseNumber,
        cardNumber: patientResponse.data.cardNumber || '',
        gender: patientResponse.data.gender,
        age: patientResponse.data.age || ''
      }
    } else {
      ElMessage.warning('未找到患者信息')
      return
    }

    // 处理收费项目响应
  if (chargeItemsResponse.success && Array.isArray(chargeItemsResponse.data)) {
      // 根据API响应格式，将techName映射到itemName，techPrice映射到price
      chargeItems.value = chargeItemsResponse.data.map(item => ({
        id: item.id,
        itemName: item.techName || '收费项目',
        price: item.techPrice || 0,
        quantity: 1 // 默认数量为1
      }))
      
      // 自动全选所有项目，确保总价正确显示
      selectedItems.value = [...chargeItems.value]
    } else {
      chargeItems.value = []
      selectedItems.value = []
      ElMessage.info('该患者暂无收费项目记录')
    }
  } catch (error) {
    console.error('搜索患者失败:', error)
    ElMessage.error('网络错误，请重试')
  } finally {
    loading.value = false
  }
}

// 获取收费项目
const getChargeItems = async (searchParams) => {
  loading.value = true
  try {
    // 根据用户提供的API响应，直接调用search接口获取收费项目
    const response = await patientApi.search(searchParams)
    
  if (response.success && Array.isArray(response.data)) {
      // 根据API响应格式，将techName映射到itemName，techPrice映射到price
      chargeItems.value = response.data.map(item => ({
        id: item.id,
        itemName: item.techName || '收费项目',
        price: item.techPrice || 0,
        quantity: 1 // 默认数量为1
      }))
      
      // 自动全选所有项目，确保总价正确显示
      selectedItems.value = [...chargeItems.value]
    } else {
      chargeItems.value = []
      selectedItems.value = []
      ElMessage.info('该患者暂无收费项目记录')
    }
  } catch (error) {
    console.error('获取收费项目失败:', error)
    chargeItems.value = []
    ElMessage.error('获取收费信息失败，请重试')
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchForm.caseNumber = ''
  searchForm.realName = ''
  patientInfo.value = null
  chargeItems.value = []
  selectedItems.value = []
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedItems.value = selection
}

// 处理结算
const handleSettle = async () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择收费项目')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要为患者 ${patientInfo.value.realName}（病历号：${patientInfo.value.caseNumber}）办理收费结算吗？总金额：${totalPrice.value}元`,
      '收费结算确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用结算接口
    const response = await chargeApi.settle({
      patientId: patientInfo.value.id,
      items: selectedItems.value.map(item => item.id),
      totalAmount: totalPrice.value
    })

  if (response.success) {
      ElMessage.success('收费结算成功')
      // 刷新收费项目列表
      await getChargeItems(searchForm)
      // 更新已结算处方的状态
      for (const item of selectedItems.value) {
        try {
          const upd = await prescriptionApi.updateById(item.id, { drugState: '已结算' })
          if(!upd.success){
            console.warn('单条处方更新失败', item.id)
          }
        } catch (error) {
          console.warn('更新处方状态失败:', error)
        }
      }
    } else {
      ElMessage.error(response.message || '收费结算失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('收费结算失败:', error)
      ElMessage.error('网络错误，请重试')
    }
  }
}
</script>

<style scoped>
.charge-container {
  padding: 20px;
  background-color: #fff;
  min-height: 100vh;
}

h1 {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e4e7ed;
}

h3 {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 15px;
  color: #303133;
}

.search-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.patient-info-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.patient-info-content p {
  margin: 0;
  padding: 5px 0;
  color: #303133;
}

.items-section {
  margin-bottom: 20px;
}

.total-price-section {
  margin-bottom: 15px;
  padding: 10px 15px;
  background-color: #e6f7ff;
  border-radius: 4px;
}

.total-price {
  display: flex;
  align-items: center;
  color: #1890ff;
}

.price-amount {
  font-weight: 600;
  margin-left: 5px;
  font-size: 16px;
}

.settle-section {
  margin-top: 15px;
  text-align: right;
}
</style>
